/**
 * 读取zip文件中的所有文件内容
 */
import common from '../../tnxet-common.js';
import util from '../main-util.js';
import fs from 'fs';
import JSZip from 'jszip';

export default {
    name: common.event.zip.readAll,
    listen(zipPath, filenamePattern) {
        return new Promise((resolve, reject) => {
            if (zipPath) {
                try {
                    zipPath = util.file.getAbsolutePathBasedOnApp(zipPath);
                    let data = fs.readFileSync(zipPath);
                    JSZip.loadAsync(data).then(zip => {
                        let all = {};
                        let filenames = Object.keys(zip.files);
                        let handledFiles = new Set();
                        for (let filename of filenames) {
                            try {
                                if (typeof filenamePattern === 'string') {
                                    let regex = new RegExp(filenamePattern);
                                    if (!regex.test(filename)) {
                                        handledFiles.add(filename);
                                        continue;
                                    }
                                }
                                let file = zip.file(filename);
                                if (file && !file.dir) {
                                    file.async('string').then(content => {
                                        all[filename] = content;
                                        handledFiles.add(filename);
                                        if (handledFiles.size === filenames.length) {
                                            resolve(all);
                                        }
                                    }).catch(error => {
                                        handledFiles.add(filename);
                                        console.error(error);
                                    });
                                } else {
                                    handledFiles.add(filename);
                                }
                            } catch (error) {
                                handledFiles.add(filename);
                                console.error(error);
                            }
                        }
                    }).catch(error => {
                        reject(error);
                    });
                } catch (error) {
                    reject(error);
                }
            } else {
                reject('zipPath is ' + zipPath);
            }
        });
    },
}
